//
//  ActivityViewController.m
//  MapList
//
//  Created by Wu Chenhao on 6/3/12.
//  Copyright (c) 2012 MicroStrategy. All rights reserved.
//

#import "ActivityViewController.h"
#import "ActivityCell.h"
#import "ActivityInfo.h"
#import "RequestUtil.h"
#import "UserMap.h"
#import "StaticInfo.h"
#import <QuartzCore/QuartzCore.h>
#import "UIColor+XMin.h"


static NSString *latestCreateTime;

@implementation ActivityViewController
@synthesize activityView=_activityView;
@synthesize activities;
@synthesize requestUtil;

@synthesize textPull, textRelease, textLoading, refreshHeaderView, refreshLabel, refreshArrow, refreshSpinner;


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.separatorStyle = NO;    
    requestUtil = [RequestUtil getSinglton];
    self.activityView=[[ActivityView alloc]init:@"加载中..." lat:self.view.frame.size.width/2 log:100];
    [self.view addSubview:self.activityView];
    [self.activityView setHidden:NO];
    [self initActivities:@"-1" createTime:@"0"];
    [self addPullToRefreshHeader];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.tableView.delegate=nil;
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait||interfaceOrientation ==UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSLog(@"count: %d", [activities count]);
    return [activities count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *OrangeCellIdentifier = @"OrangeCell";
    static NSString *BlueCellIdentifier = @"BlueCell";
    ActivityInfo *actInfo = [activities objectAtIndex:indexPath.row];
    //ActivityCell *cell;
    //暂时的解决办法。。。部重用cell
    ActivityCell *cell = [tableView dequeueReusableCellWithIdentifier:OrangeCellIdentifier];
    
    NSInteger thisTag = 100 * [indexPath section] + [indexPath row];
    NSLog(@"activities count = : %d", [actInfo.status intValue]);
    if ([actInfo.status intValue] == 10) {
        cell = [[ActivityCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:OrangeCellIdentifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        if (actInfo.isLeader) {
        cell.wanchengButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [cell.wanchengButton setFrame:CGRectMake(25, 25, 99, 22)];
        [cell.wanchengButton setBackgroundImage:[UIImage imageNamed:@"finish.png"] forState:UIControlStateNormal];
        [cell.wanchengButton addTarget:self action:@selector(wanchengButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [cell.panel3 addSubview:cell.wanchengButton];
        cell.wanchengButton.tag = thisTag;
        }
        cell.tuichuButton = [UIButton buttonWithType:UIButtonTypeCustom];
        if(actInfo.isLeader){
            [cell.tuichuButton setFrame:CGRectMake(175, 25, 99, 22)];
        }else{
            [cell.tuichuButton setFrame:CGRectMake(95, 25, 99, 22)];
        }
        [cell.tuichuButton setBackgroundImage:[UIImage imageNamed:@"quit.png"] forState:UIControlStateNormal];
        [cell.tuichuButton addTarget:self action:@selector(tuichuButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [cell.panel3 addSubview:cell.tuichuButton];
        cell.tuichuButton.tag = thisTag;
        cell.tag = thisTag;
        cell.actNameLabel.text = actInfo.name;
        cell.locationLabel.text = actInfo.beginLocation;
        cell.distanceLabel.text = [NSString stringWithFormat:@"%0.1lf KM",[actInfo distance]];
        
        UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(1, 0, 299, 110)];
        [selectedBackgroundView setBackgroundColor:[UIColor blackColor]];
        [cell setSelectedBackgroundView:selectedBackgroundView];
    }
    
    else if ([actInfo.status intValue] == 20){
        cell = [[ActivityCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:BlueCellIdentifier];
        
        cell.actNameLabel.text = actInfo.name;
        cell.locationLabel.text = actInfo.beginLocation;
        cell.distanceLabel.text = [NSString stringWithFormat:@"%0.1lf KM",[actInfo distance]];
    }
    return cell;
}



- (void)wanchengButtonClicked:(UIButton *)button
{
    [MobClick event:@"2012070206"];
    NSArray *visibleCells = [self.tableView visibleCells];
	for(ActivityCell *cell in visibleCells) {
		if(cell.tag == button.tag) {
			NSIndexPath *path = [self.tableView indexPathForCell:cell];
            ActivityInfo *actInfo = [activities objectAtIndex:path.row];
            NSNumber *num = [[NSNumber alloc] initWithInt:20];
            [actInfo setStatus:num];
            [requestUtil finishActivity:[[actInfo id] stringValue]];
            [cell collapsEditPanel];
            double totalDistance=[[StaticInfo getSinglton].user.totalDistance doubleValue]/1000;
            double distance=actInfo.distance+totalDistance;
            NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:@"%0.1lf KM",distance],@"distance", nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kFinishNotification object:self userInfo:dic];
            break;
		}
	}
    
    [self sortActivities];
    [self.tableView reloadData];
    self.tableView.contentSize=CGSizeMake(320, ([activities count]+1)*110+REFRESH_HEADER_HEIGHT);
}

- (void)tuichuButtonClicked:(UIButton *)button
{
    [MobClick event:@"2012070207"];
    NSArray *visibleCells = [self.tableView visibleCells];
	for(ActivityCell *cell in visibleCells) {
		if(cell.tag == button.tag) {
			NSIndexPath *path = [self.tableView indexPathForCell:cell];
            ActivityInfo *actInfo = [activities objectAtIndex:path.row];
            NSLog(@"riddingId: %d", [[actInfo id] intValue]);
            int statusCode = [requestUtil quitActivity:[[actInfo id] stringValue]];
            NSLog(@"%d",statusCode);
            if (statusCode ==-300) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"退出失败" 
                                                                message:@"请在退出之前确认其他队员均已退出" 
                                                               delegate:self cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }else if(statusCode<0){
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" 
                                                                message:@"退出失败" 
                                                               delegate:self cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }else{
                [activities removeObjectAtIndex:path.row];
            }
            [cell collapsEditPanel];
            break;
        }
	}
    [self sortActivities];
    [self.tableView reloadData];
     self.tableView.contentSize=CGSizeMake(320, ([activities count]+1)*110+REFRESH_HEADER_HEIGHT);
}

- (void)editButtonTap:(UIGestureRecognizer *)gestureRecognizer
{
    ActivityCell *cell = (ActivityCell *)gestureRecognizer.view;
    if (cell.editButton.image == cell.editImage1) cell.editButton.image = cell.editImage2;
    else cell.editButton.image = cell.editImage1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ActivityInfo *actInfo = [activities objectAtIndex:indexPath.row];
    UserMap *userMap = [[UserMap alloc]initWithNibName:@"UserMap" bundle:nil];
    userMap.riddingId = [actInfo.id stringValue];
    NSLog(@"%d",[actInfo.status intValue]);
    userMap.riddingStatus=actInfo.status;
    RiddingAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    [appDelegate.navController pushViewController:userMap animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark - Init Activities
-(void)initActivities:(NSString*)limit createTime:(NSString*)createTime{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *array = [requestUtil getUserMaps:limit createTime:createTime];
        latestCreateTime = [[[array objectAtIndex:0] objectForKey:@"createtime"]stringValue];
        if(array&&[array count]>0){
            activities = [[NSMutableArray alloc] init];
            for (NSDictionary *dic in array) {
                ActivityInfo *actInfo = [[ActivityInfo alloc] init];
                actInfo.name = [dic objectForKey:@"name"];
                actInfo.id = [dic objectForKey:@"id"];
                actInfo.distance = [[dic objectForKey:@"distance"] doubleValue]/1000;
                actInfo.status = [dic objectForKey:@"status"];
                actInfo.name = [dic objectForKey:@"name"];
                actInfo.beginLocation = [dic objectForKey:@"beginLocation"];
                actInfo.createTime = [dic objectForKey:@"createtime"];
                NSNumber *userRole = [dic objectForKey:@"userRole"];
                if ([userRole intValue] == 20) {
                    actInfo.isLeader = YES;
                }
                else actInfo.isLeader = NO;
                [activities addObject:actInfo];
            }
        }
        [self sortActivities];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
             self.tableView.contentSize=CGSizeMake(320, ([activities count]+1)*110+REFRESH_HEADER_HEIGHT);
             [self.activityView setHidden:YES];
        });
    });
    
}

-(void)reloadActivities:(NSString*)limit createTime:(NSString*)createTime{
    NSLog(@"latestCreateTime===== %@", latestCreateTime);
    if (!createTime) {
        createTime = @"0";
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *array = [requestUtil getUserMaps:limit createTime:createTime];
        if(array&&[array count]>0){
            latestCreateTime = [[[array objectAtIndex:0] objectForKey:@"createtime"]stringValue];
            for (NSDictionary *dic in array) {
                ActivityInfo *actInfo = [[ActivityInfo alloc] init];
                actInfo.name = [dic objectForKey:@"name"];
                actInfo.id = [dic objectForKey:@"id"];
                actInfo.distance = [[dic objectForKey:@"distance"] doubleValue]/1000;
                actInfo.status = [dic objectForKey:@"status"];
                actInfo.name = [dic objectForKey:@"name"];
                actInfo.beginLocation = [dic objectForKey:@"beginLocation"];
                actInfo.createTime = [dic objectForKey:@"createtime"];
                NSNumber *userRole = [dic objectForKey:@"userRole"];
                if ([userRole intValue] == 20) {
                    actInfo.isLeader = YES;
                }
                else actInfo.isLeader = NO;
                [activities addObject:actInfo];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self sortActivities];
            [self.tableView reloadData];
            self.tableView.contentSize=CGSizeMake(320, ([activities count]+1)*110+REFRESH_HEADER_HEIGHT);
        });
    });

}
//uncompleted in the top and completed in the bottom
- (void) sortActivities{
    NSArray *sortDescriptors = [NSArray arrayWithObjects:
                                 [NSSortDescriptor sortDescriptorWithKey:@"status" ascending:YES],[NSSortDescriptor sortDescriptorWithKey:@"createTime" ascending:NO], nil];
    [activities sortUsingDescriptors:sortDescriptors];
//    sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"createTime" ascending:NO]];
//    [activities sortUsingDescriptors:sortDescriptors];
                       
}


#pragma mark-
#pragma mark Pull to Refresh
- (void)addPullToRefreshHeader{
    textPull = [[NSString alloc] initWithString:@"下拉刷新..."];
    textRelease = [[NSString alloc] initWithString:@"释放刷新..."];
    textLoading = [[NSString alloc] initWithString:@"载入中..."];
    
    refreshHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0 - REFRESH_HEADER_HEIGHT, 300, REFRESH_HEADER_HEIGHT)];
    refreshHeaderView.backgroundColor = [UIColor clearColor];
    
    refreshLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, REFRESH_HEADER_HEIGHT)];
    refreshLabel.backgroundColor = [UIColor clearColor];
    refreshLabel.font = [UIFont boldSystemFontOfSize:12.0];
    refreshLabel.textAlignment = UITextAlignmentCenter;
    refreshLabel.textColor=[UIColor getColor:@"#E5E5E5"];
    
    refreshArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"]];
    refreshArrow.frame = CGRectMake((REFRESH_HEADER_HEIGHT - 27) / 2,
                                    (REFRESH_HEADER_HEIGHT - 44) / 2,
                                    27, 44);
    
    refreshSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    refreshSpinner.frame = CGRectMake((REFRESH_HEADER_HEIGHT - 20) / 2, (REFRESH_HEADER_HEIGHT - 20) / 2, 20, 20);
    refreshSpinner.hidesWhenStopped = YES;
    
    [refreshHeaderView addSubview:refreshLabel];
    [refreshHeaderView addSubview:refreshArrow];
    [refreshHeaderView addSubview:refreshSpinner];
    
    [self.tableView addSubview:refreshHeaderView];
    //[self.view bringSubviewToFront:refreshHeaderView];
    
}

- (void)startLoading{
    isLoading = YES;
    // Show the header
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    self.tableView.contentInset = UIEdgeInsetsMake(REFRESH_HEADER_HEIGHT, 0, 0, 0);
    refreshLabel.text = self.textLoading;
    refreshArrow.hidden = YES;
    [refreshSpinner startAnimating];
    [UIView commitAnimations];
    
    // Refresh action!
    [self refresh];
}

- (void)stopLoadingComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    // Reset the header
    refreshLabel.text = self.textPull;
   
    refreshArrow.hidden = NO;
    [refreshSpinner stopAnimating];
}

- (void)stopLoading{
    isLoading = NO;
    
    // Hide the header
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDidStopSelector:@selector(stopLoadingComplete:finished:context:)];
    self.tableView.contentInset = UIEdgeInsetsZero;
    [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI * 2, 0, 0, 1);
    
    [UIView commitAnimations];
}

//- (void)refresh{
//    // This is just a demo. Override this method with your custom reload action.
//    // Don't forget to call stopLoading at the end.
//    [self performSelector:@selector(stopLoading) withObject:nil afterDelay:2.0];
//}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (isLoading) {
        return;  
    }
    isDragging = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSLog(@"%f", scrollView.contentOffset.y);
    if (isLoading) {
        // Update the content inset, good for section headers
        if (scrollView.contentOffset.y > 0)
            self.tableView.contentInset = UIEdgeInsetsZero;
        else if (scrollView.contentOffset.y >= -REFRESH_HEADER_HEIGHT)
            self.tableView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (isDragging && scrollView.contentOffset.y < 0) {
        // Update the arrow direction and label
        [UIView beginAnimations:nil context:NULL];
        if (scrollView.contentOffset.y < -REFRESH_HEADER_HEIGHT) {
            // User is scrolling above the header
            refreshLabel.text = self.textRelease;
            [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI, 0, 0, 1);
        } else { // User is scrolling somewhere within the header
            refreshLabel.text = self.textPull;
            [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI * 2, 0, 0, 1);
        }
        [UIView commitAnimations];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (isLoading) return;
    isDragging = NO;
    if (scrollView.contentOffset.y <= -REFRESH_HEADER_HEIGHT) {
        // Released above the header
        [self startLoading];
    }
}

- (void)refresh {
    [self performSelector:@selector(addItem) withObject:nil afterDelay:2.0];
}

- (void)addItem {
    // Add a new time
    [self reloadActivities:@"-1" createTime:latestCreateTime];
    [self stopLoading];

}

@end
